const multer = require("multer");
const storage = require("../storage");
const moment = require("moment/moment"); // 假设你已经有了存储配置模块
const upload = multer({ storage });
async function addImage(req, res) {
    try {
        // 使用multer处理上传的图片
        const uploadedFile = await new Promise((resolve, reject) => {
            upload.single("avatar")(req, res, (err) => {
                if (err) return reject(err);
                resolve(req.file);
            });
        });
        // 获取上传图片的基本信息
        const { filename } = uploadedFile;
        const protocol = req.protocol;
        const hostname = req.hostname; // 获取当前请求的
        const dateStr = moment().format("YYYY-MM-DD"); //获取上传时当前日期
        const port = req.socket.localPort; // 获取当前请求的端口号
         const imageUrl = `${protocol}://${hostname}:${port}/${dateStr}/${filename}`; // 构造当前请求的完整 URL
        res.send({
            code: 200,
            data: {
                imageUrl,
            },
            msg: "图片上传成功",
        });
    } catch (error) {
        console.error(error);
        res.status(500).send({
            code: 500,
            msg: "图片上传失败，请检查服务器错误",
        });
    }
}

module.exports = { addImage };
